package com.yunduan.tornado.controller.bank;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yunduan.tornado.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jinpeng
 * @since 2019-09-04
 */
@RestController
@RequestMapping("bankUser")
@Slf4j
public class UserBankController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public  String  login(String userName,String password){
        //生成shiro凭证

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        Subject currentUser  = SecurityUtils.getSubject();
        // 验证凭证是否有效
        try {
            currentUser .login(token);
        } catch (AuthenticationException e) {
            log.error("登录失败",e);
            return  "登录失败";
        }
        return "登录成功";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String loginSuccessMessage(HttpServletRequest request) {
        String username = "未登录";
        Subject subject = SecurityUtils.getSubject();
        User user =new User();
        if (subject.isAuthenticated()) {
            Object principal = subject.getPrincipals().getPrimaryPrincipal();
            if (principal instanceof User) {
                user =   (User) principal;
            }
        }

        if (user != null && StringUtils.isNotEmpty(user.getUserName())) {
            username = user.getUserName();
        } else {
            return "redirect:/auth/login";
        }
        request.setAttribute("username", username);
        return "index";
    }

    //被踢出后跳转的页面
    @RequestMapping(value = "/kickout", method = RequestMethod.GET)
    public String kickOut() {
        return "kickout";
    }

}
